#include <init/IRQ.h>
#include <init/PIT.h>
#include <video/VGA.h>
#include <string.h>
#include <asmutils.h>

/* This will keep track of how many ticks that the system
 *  has been running for */
_u32 timer_ticks = 0;
_u32 seconds = 0;

// placed in linker file
extern _u32 end;

// kernel end address
_u32 kend_address = (_u32)&end;

void timer_phase(_s32 hz)
{
  _s32 divisor = 1193180 / hz;       /* Calculate our divisor */
  outb(0x43, 0x36);                  /* Set our command byte 0x36 */
  outb(0x40, divisor & 0xFF);        /* Set low byte of divisor */
  outb(0x40, divisor >> 8);          /* Set high byte of divisor */
}		

/* Handles the timer by increment the 'timer_ticks' variable every time the
*  timer fires. By default, the timer fires 18.222 times
*  per second. */
void timer_handler(struct registers *r)
{

  /* Increment our 'tick count' */
  timer_ticks++;
	
  /* Every 18 clocks is approximately 1 second at default frequency */
  if (timer_ticks % 18 == 0)
  {
//    cls();
//    printk("Clock ticks elapsed: %d, seconds elapsed: %d\n", timer_ticks, ++seconds);
//    printk("Kernel end address: %d\n", kend_address);
  }
}
    
/* This will continuously loop until the given time has
 *  been reached */
void timer_wait(_s32 ticks)
{
  _u32 eticks;
					
  eticks = timer_ticks + ticks;
  while(timer_ticks < eticks);
}

/* Sets up the system clock by installing the timer handler
 * into IRQ0 */
void timer_install()
{
  /* Installs 'timer_handler' to IRQ0 */
  irq_install_handler(0, timer_handler);
}
